<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NSpace>
              <NForm ref="formRef" :model="formValue" :rules="rules" label-placement="left" :label-width="100"
                label-align="right" require-mark-placement="left">
                <NFormItem label="用车类型:" path="carStatus">
                  <NSelect v-model:value="formValue.carStatus" placeholder="选择用车类型" :options="carOptions" clearable />
                </NFormItem>
                <NFormItem label="名称:" path="carName">
                  <NInput v-model:value="formValue.carName" placeholder="输入名称" class="commonWidth"
                    :allow-input="stopNull" />
                </NFormItem>
                <NFormItem label="车牌号:" path="licensePlate">
                  <NInput v-model:value="formValue.licensePlate" placeholder="输入车牌号" class="commonWidth"
                    :allow-input="stopNull" />
                </NFormItem>
                <NFormItem label="备注:" path="remarks">
                  <NInput v-model:value="formValue.remarks" placeholder="请输入备注" type="textarea" class="commonWidth"
                    style="min-height: 130rem" :allow-input="stopNull" />
                </NFormItem>
              </NForm>
            </NSpace>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        取消
      </NButton>
      <NButton type="primary" @click="confirm">
        保存
      </NButton>
    </NSpace>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要保存吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSpin,
  useMessage,
  NModal,
  NSelect
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const tags = useTagStore().tags

const props = defineProps({
  id: {
    type: [Number, String]
  },
  title: {
    type: String
  }
})

const formRef = ref<FormInst | null>(null)
const formValue = ref({
  carName: '',
  licensePlate: '',
  remarks: '',
  carStatus: ''
})
const rules: any = ref(
  {
    carStatus: {
      required: true,
      trigger: ['blur', 'change'],
      message: '选择用车类型'
    },
    carName: {
      required: true,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        if (value.length == 0) return new Error('请输入车辆名称')
        if (value.length > 100) return new Error('车辆名称不得超过100')
        return true
      }
    },
    licensePlate: {
      required: formValue.value.carStatus == '1' ? true : false,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        // if (value.length == 0) return new Error('请输入车牌号')
        if (value.length > 100) return new Error('车牌号不得超过100')
        return true
      }
    },
    remarks: {
      required: formValue.value.carStatus == '2' ? true : false,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        if (formValue.value.carStatus == '2' && value.length == 0) return new Error('请输入备注')
        if (value.length > 100) return new Error('备注字数不得超过100')
        return true
      }
    }
  }
)

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

watch(formValue.value, () => {
  rules.value = {
    carStatus: {
      required: true,
      trigger: ['blur', 'change'],
      message: '选择用车类型'
    },
    carName: {
      required: true,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        if (value.length == 0) return new Error('请输入车辆名称')
        if (value.length > 100) return new Error('车辆名称不得超过100')
        return true
      }
    },
    licensePlate: {
      required: formValue.value.carStatus == '1' ? true : false,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        if (value.length == 0 && formValue.value.carStatus == '1') return new Error('请输入车牌号')
        if (value.length > 100) return new Error('车牌号不得超过100')
        return true
      }
    },
    remarks: {
      required: formValue.value.carStatus == '2' ? true : false,
      trigger: ['input', 'blur'],
      validator: (_: any, value: any) => {
        if (value.length == 0 && formValue.value.carStatus == '2') return new Error('请输入备注')
        if (value.length > 100) return new Error('备注字数不得超过100')
        return true
      }
    }
  }
})

const carOptions = [
  {
    label: '馆内用车',
    value: '1'
  },
  {
    label: '租车',
    value: '2'
  }
]

//车辆信息
const spinShow = ref(false)
const getInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'office',
    api: 'carItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code != 0) return message.error(res.msg)
  const tmp: any = res.data
  if (tmp) {
    formValue.value.carName = tmp?.carName
    formValue.value.licensePlate = tmp?.licensePlate
    formValue.value.remarks = tmp?.remarks
    formValue.value.carStatus = tmp?.carStatus === 2 || tmp?.carStatus === 1 ? tmp?.carStatus + '' : null as never
  }
  spinShow.value = false
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  router.push({ path: '/OA/Office/carSetting' })
}
// 确定
const modalVisible = ref(false)
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  if (!props.id) {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'office',
      api: 'carSave',
      override: {
        data: {
          ...formValue.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
  } else {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'office',
      api: 'carUpdate',
      override: {
        data: {
          id: props.id,
          ...formValue.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
  }
  modalVisible.value = false
  goBack()
}

watch(
  () => props.id,
  () => {
    if (props.id && props.title == "用车编辑") getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
